﻿using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Integration;
using Sinacor.Infra.UI.Common;
using Sinacor.Infra.UI.Controls.SmartClient;
using Sinacor.UI.Application.Settings.SmartClient;
using Sinacor.UI.HelpViewer.Service;

namespace Sinacor.UI.HelpViewer.View
{
	public partial class Viewer : SinacorWindowHelp
	{
		#region Attributes

		Receiver pipe = new Receiver();
		ApplicationSettings _applicationSettings = ApplicationSettings.GetInstance();

		#endregion

		#region Constructor

		public Viewer()
		{
			InitializeComponent();

			this.Loaded += new RoutedEventHandler(Viewer_Loaded);
			this.tabControl.SinacorTabItemBrowserAdded += new RoutedEventHandler(tabControl_TabItemAdded);

			this.webBrowser.DownloadComplete += new EventHandler(webBrowser_DownloadComplete);
			this.webBrowser.StartNewWindow += new EventHandler<BrowserExtendedNavigatingEventArgs>(webBrowser_StartNewWindow);

			pipe.DocumentHelpReady = new PipeService.DocumentHelpReadyEventHandler(DocumentHelpRecieved);
			pipe.LanguageChanged = new PipeService.LanguageChangedEventHandler(NewLanguageRecieved);
			pipe.ThemeChanged = new PipeService.ThemeChangedEventHandler(NewThemeRecieved);

			if (!pipe.ServiceOn())
				SinacorMessageBox.Show(pipe.error.Message, SinacorMessageBoxButton.Ok, SinacorMessageBoxImage.Error);
		}

		#endregion

		#region Events

		private void Viewer_Loaded(object sender, RoutedEventArgs e)
		{
			if (tabControl.SelectedItem != null)
			{
				ExtendedWebBrowser browser = GetCurrentBrowser();
				SetSourceIndexPanel();
				SetSource(browser, "WelcomePage");
			}
		}

		private ExtendedWebBrowser GetCurrentBrowser()
		{
			return (ExtendedWebBrowser)(((WindowsFormsHost)(((SinacorTabItemBrowser)tabControl.SelectedItem).Content)).Child);
		}

		private ExtendedWebBrowser GetCurrentBrowser(SinacorTabItemBrowser tabItem)
		{
			return (ExtendedWebBrowser)(((WindowsFormsHost)(tabItem.Content)).Child);
		}

		private void tabControl_TabItemAdded(object sender, RoutedEventArgs e)
		{
			SinacorTabItemBrowser item = (SinacorTabItemBrowser)(sender as SinacorTabControlBrowser).SelectedItem;

			TextBlock tb = new TextBlock();
			tb.Text = FindResource("Infra.Controls.Label.NovaAba").ToString();
			tb.TextTrimming = TextTrimming.CharacterEllipsis;
			tb.TextWrapping = TextWrapping.NoWrap;
			item.Header = tb;

			WindowsFormsHost host = new WindowsFormsHost();
			ExtendedWebBrowser browser = new ExtendedWebBrowser();
			browser.DownloadComplete += new EventHandler(webBrowser_DownloadComplete);
			browser.StartNewWindow += new EventHandler<BrowserExtendedNavigatingEventArgs>(webBrowser_StartNewWindow);
			SetSource(browser, "WelcomePage");
			host.Child = browser;
			item.Content = host;
		}

		private void webBrowser_StartNewWindow(object sender, BrowserExtendedNavigatingEventArgs e)
		{
			tabControl.AddTabItem();
			ExtendedWebBrowser browser = GetCurrentBrowser();

			//int indexHelp = e.Url.ToString().IndexOf("Help");
			//int numeroCasas = 11; // Help/pt-br/
			//string name = e.Url.ToString().Substring(indexHelp + numeroCasas, e.Url.ToString().Length - indexHelp - numeroCasas);
			//name = name.Substring(0, name.LastIndexOf('.'));

			SetSource(browser, e.Url.AbsolutePath.ToString());
			e.Cancel = true;
		}

		private void webBrowser_DownloadComplete(object sender, EventArgs e)
		{
			int lastItemIndex = (tabControl.Items.Count - 1);
			SinacorTabItemBrowser item = (SinacorTabItemBrowser)tabControl.Items[lastItemIndex];
			ExtendedWebBrowser browser = GetCurrentBrowser(item);
			((TextBlock)item.Header).Text = browser.Document.Title;

			item.IsSelected = true;
			tabControl.SelectedItem = item;
			tabControl.SelectedIndex = lastItemIndex;
			UpdateLayout();
			item.Focus();
		}

		private void OnIndexPanelSelectedItemChanged(Uri location)
		{
			if (tabControl.SelectedItem == null)
				tabControl.AddTabItem();

			ExtendedWebBrowser browser = GetCurrentBrowser();

			//string name = location.ToString().Substring(0, location.ToString().LastIndexOf('.'));

			SetSource(browser, location.ToString());
		}

		private void OnTabControlSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (tabControl.SelectedItem == null)
				if (tabControl.HasItems == false)
					DisableNavigationButtons();
		}

		private void CurrentTabGoBack(object sender, RoutedEventArgs args)
		{
			if (tabControl.SelectedItem != null)
			{
				ExtendedWebBrowser browser = GetCurrentBrowser();

				if (browser.CanGoBack)
					browser.GoBack();
			}
			else
				DisableNavigationButtons();
		}

		private void CurrentTabGoForward(object sender, RoutedEventArgs args)
		{
			if (tabControl.SelectedItem != null)
			{
				ExtendedWebBrowser browser = GetCurrentBrowser();

				if (browser.CanGoForward)
					browser.GoForward();
			}
			else
				DisableNavigationButtons();
		}

		#endregion

		#region Methods

		private void DocumentHelpRecieved(string document)
		{
			this.Dispatcher.Invoke(new Action<string>(ChangeDocumentHelp), document);
		}

		private void NewLanguageRecieved(string language)
		{
			this.Dispatcher.Invoke(new Action<string>(ChangeLanguage), language);
		}

		private void NewThemeRecieved(string theme)
		{
			this.Dispatcher.Invoke(new Action<string>(ChangeTheme), theme);
		}

		private void ChangeDocumentHelp(string document)
		{
			tabControl.AddTabItem();
			ExtendedWebBrowser browser = GetCurrentBrowser();
			SetSource(browser, document);
			this.Activate();
		}

		private void ChangeLanguage(string language)
		{
			_applicationSettings.ChangeLanguage(language);

			foreach (SinacorTabItemBrowser item in tabControl.Items)
			{
				ExtendedWebBrowser browser = (ExtendedWebBrowser)item.Content;
				SetSource(browser, browser.Tag.ToString());
				SetSourceIndexPanel();
			}
		}

		private void ChangeTheme(string theme)
		{
			_applicationSettings.ChangeTheme(theme);
		}

		private void SetSourceIndexPanel()
		{
			indexPanel.NavigationMapSource = new Uri(string.Format("pack://siteoforigin:,,,/Help/{0}/toc.hxt", _applicationSettings.CurrentLanguage));
		}

		private void SetSource(ExtendedWebBrowser browser, string document)
		{
			string link = GetSource(document);

			if (link != string.Empty)
			{
				browser.Navigate(link);
				browser.Tag = document;
			}
		}

		private string GetSource(string document)
		{
			string file = string.Concat(System.Windows.Forms.Application.StartupPath, @"\\{0}\Help\{1}\{2}");
			string fileName = string.Empty;
			string extension = ".html";
			string[] docs = document.Split("/".ToCharArray());

			if (!File.Exists(document))
			{
				if (docs.Length == 2)
				{
					ModuleInformation module = _applicationSettings.InstalledModules.ToList().Find(m => m.Name == docs[0]);

					if (module != null)
						fileName = Path.GetFullPath(String.Format(file, module.Folder, _applicationSettings.CurrentLanguage, docs[1]));
				}
				else if (docs.Length == 1)
					fileName = Path.GetFullPath(String.Format(file, string.Empty, _applicationSettings.CurrentLanguage, docs[0]));

				if (!fileName.Contains(extension))
					fileName = fileName + extension;

				if (!File.Exists(Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName)) + extension))
				{
					fileName = Path.GetFullPath(String.Format(file, string.Empty, _applicationSettings.CurrentLanguage, "PageNotFound") + extension);

					//if (!File.Exists(fileName))
					//    SinacorMessageBox.Show(String.Format((string)FindResource("Infra.UI.Message.ArquivoHelpNaoEncontrado"), fileName), SinacorMessageBoxButton.Ok, SinacorMessageBoxImage.Error);
				}
			}
			else
				fileName = document;

			return fileName;
		}

		private void DisableNavigationButtons()
		{
			Button GoBackButton = (ControlHelper.FindChild(grpMain, "GoBackButton") as Button);
			Button GoForwardButton = (ControlHelper.FindChild(grpMain, "GoForwardButton") as Button);

			if (GoBackButton != null)
				GoBackButton.IsEnabled = false;

			if (GoForwardButton != null)
				GoForwardButton.IsEnabled = false;
		}

		#endregion
	}
}